const WebSocket = require('ws')
function WebSocketUtil() {
    const thiz = this
    this.messageFunc = null
    this.messageObject = null
    const ipAddress = "ws://127.0.0.1:8066"
    //const client =
    this.initClient = function () {
        this.client = new WebSocket(ipAddress)
        // 建立连接
        this.client.on('open', () => {
            console.log('已连接上服务器!')
            //ws.send('Hello, server!');
        })
        // 断开连接
        this.client.on('close', () => {
            console.log('连接已断开!')
        })
        // 监听服务器返回消息
        this.client.on('message', e => {
            console.log('服务端返回的消息:', e.toString())
            if(thiz.messageFunc){
                let obj = JSON.parse(e.toString())
                thiz.messageFunc.call(thiz.messageObject, obj)
            }
        })
        // 异常错误
        this.client.on('error', e => {
            console.log('客户端错误:', e.message)
        })
    }
    /**
     * 服务端发送消息
     * @param msg
     * @param func
     * @param object
     */
    this.sendMessage = function (msg, func, object) {
        if(!this.client){
            console.log('未初始化客户端，发送消息失败')
            return
        }
        const strMsg = JSON.stringify(msg)
        console.log('sendMessage', strMsg)
        this.messageFunc = func
        this.messageObject = object
        this.client.send(strMsg)
        console.log('发送消息到服务端')
    }
}
export default new WebSocketUtil()
